package com.tianzj.mvc.leave.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.tianzj.mvc.leave.dao.OaLeaveMapper;
import com.tianzj.mvc.leave.pojo.OaLeave;
import com.tianzj.mvc.leave.pojo.OaLeaveExample;
import com.tianzj.mvc.leave.service.LeaveService;
import com.tianzj.mvc.util.SessionUser;
import com.tianzj.util.Page;
import com.tianzj.util.SnowflakeIdWorker;

@Service
public class LeaveServiceImpl implements LeaveService {
	
	@Autowired
	private OaLeaveMapper oaLeaveMapper;
	
	@Autowired
	private IdentityService identityService;

	@Autowired
	private RuntimeService runtimeService;

	public OaLeaveExample getExample(OaLeave  oaleave){
		OaLeaveExample example=new OaLeaveExample();
		OaLeaveExample.Criteria criteria = example.createCriteria();
		if(oaleave.getCreateUser()!=null){
			criteria.andIdEqualTo(oaleave.getCreateTime());
		}
		if(oaleave.getStatus()!=null){
			criteria.andStatusEqualTo(oaleave.getStatus());
		}else{
			criteria.andStatusNotEqualTo(9L);
		}
		return example;
	}
	@Override
	public List<OaLeave> getLeaveList(Page page, OaLeave oaleave) {
		PageHelper.startPage(page.getPageNum(),page.getPageSize());
		return oaLeaveMapper.selectByExample(getExample(oaleave));
	}
	
	@Override
	public void addLeave(OaLeave leave) {
		leave.setId(new SnowflakeIdWorker(0, 0).nextId());
		leave.setCreateTime(System.currentTimeMillis());
		leave.setCreateUser(SessionUser.getUser().getId());
		leave.setStatus(0L);
		leave.setCreateUserName(SessionUser.getUser().getUserName());
		oaLeaveMapper.insertSelective(leave);
	}
	@Override
	public void startLeaveAct(String id) {
		OaLeave oaleave =getById(id);
		if(oaleave.getStatus().longValue()==0){
			oaleave.setApplyTime(System.currentTimeMillis());
			oaleave.setStatus(1L);
			
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(SessionUser.getUser().getId().toString());
			
			// 启动流程
			Map<String, Object> variables = new HashMap<>();
			String businessKey = oaleave.getId().toString();
			variables.put("type", "leave");
			variables.put("busId", businessKey);
			variables.put("manager", "admin");
			
			//启动流程实例
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leave", businessKey, variables);
			oaleave.setProcessInstanceId(processInstance.getId());
			oaLeaveMapper.updateByPrimaryKeySelective(oaleave);
		}
	}
	
	private OaLeave getById(String id) {
		return oaLeaveMapper.selectByPrimaryKey(Long.parseLong(id));
	}

}
